package com.app.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.app.config.Settings;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.nio.charset.StandardCharsets;

@Component//单例设计模式
public class TokenManager {
    private JedisPool jedisPool;
    private Jedis jedis;

    public TokenManager(JedisPool jedisPool) {
        this.jedisPool=jedisPool;
        if (jedisPool.isClosed()){
            System.out.println("redis 没有连接");
        }else {
            System.out.println("redis 已连接");
            jedis=jedisPool.getResource();
            jedis.select(9);
        }
    }

    private Jedis checkJedis(){
        if (!jedis.isConnected()||jedis.isBroken()){
            jedis.close();
            jedis=jedisPool.getResource();
            jedis.select(9);
            System.out.println(this+"---->刷新： "+jedis);
        }
        return jedis;
    }
    /**
     * 根据token获取已经连接的用户id，失效则返回null
     * @param token
     * @return: userId
     * @author: 本小蛋
     * @time: 2021/8/16 11:28
     */
    public boolean isLogged (String userId,String token){
        if (token==null||userId==null) return false;
        checkJedis();
        String tk = jedis.get(userId);
        if (tk!=null&&tk.equals(token)){
            jedis.expire(token,Settings.cookie_alive_second);
            return true;
        }else if (tk!=null) jedis.del(userId);
        return false;
    }
    /**
     * 添加一个登陆状态记录
     * @param userId 用户 id
     * @return: token
     * @author: 本小蛋
     * @time: 2021/8/16 12:09
     */
    public String addLoginState(String userId,String password){
        HMac mac =new HMac(HmacAlgorithm.HmacMD5, password.getBytes(StandardCharsets.UTF_8));
        String token = mac.digestHex(((int)(Math.random()*1000000)+userId))+DigestUtil.md5Hex16(password);
        checkJedis().set(userId,token,new SetParams().ex(Settings.cookie_alive_second));
        return token;
    }
}
